package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMessage(@RequestBody User user, HttpSession session) {
        if (user.getPhone() == null) {
            return R.error("手机号不存在");
        }
        //1.获取手机号
        String phone = user.getPhone();
        //2.生成验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        log.info("code = {}", code);
        //4.发送短信
        //SMSUtils.sendMessage("瑞吉外卖","",phone,code);

        //5.存储到Session
        //session.setAttribute(phone, code);

        //存储到redis,5分钟后失效
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return R.success("短信发送成功");
    }

    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //1、获取手机号
        String phone = (String) map.get("phone");
        //2、获取验证码
        String code = (String) map.get("code");
        //3、比对是否正确
        //从Session中获取短信验证码
        //String codeInSession = session.getAttribute(phone).toString();

        //从Redis中获取短信验证码
        String codeInSession = redisTemplate.opsForValue().get(phone).toString();

        if (codeInSession != null && code.equals(codeInSession)){
            //4、正确则检查用户是否存在
            LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
            lqw.eq(User::getPhone,phone);
            User user = userService.getOne(lqw);
            //5、用户不存在就新建用户在数据库
            if (user == null){
                user = new User();
                user.setPhone(phone);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());

            //用户登陆成功,则从redis中删除验证码
            redisTemplate.delete(phone);
            return R.success(user);

        }



        return R.error("用户登陆失败");
    }

}
